<?php
namespace Controller;

use Core\Controller, Lib;

class Email extends Controller {
	private $MEmail = NULL;

	public function __construct() {
		$this->MEmail = \Model\Email::getInstance();
	}

	public function index() {
		$label = isset($_GET['label']) ? $_GET['label'] : '';
		
		$batch = $this->MEmail->getBatch();
		
		foreach ($batch as $key => &$item) {
			$item['count'] = $this->MEmail->count($item['batch']);
		}
		
		$this->assign('label', $label);
		$this->assign('batch', $batch);
		
		$this->display();
	}

	public function import() {
		$batch = trim($_GET['batch']);
		
		$batch || die('Error: batch not empty.');
		
		if ($this->MEmail->count($batch) > 0) {
			die('Error: batch is non-empty.');
		}
		
		echo $this->MEmail->import($batch) ? $this->MEmail->count($batch) : 'Error';
	}

	public function delete() {
		$batch = isset($_GET['batch']) ? trim($_GET['batch']) : '';
		$host = isset($_GET['host']) ? trim($_GET['host']) : '';
		
		echo $this->MEmail->delete($batch, $host) ? 'OK' : 'Error';
	}

	public function host() {
		$batch = trim($_GET['batch']);
		$label = isset($_GET['label']) ? trim($_GET['label']) : '';
		$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 0;
		
		if (isset($_GET['always'])) {
			$always = $_GET['always'] ? explode(',', trim($_GET['always'])) : array();
		} else {
			$always = array('qq.com', 'vip.qq.com', '163.com', 'vip.163.com', '126.com', 'gmail.com', 'sina.cn', 'sina.com', 'sina.com.cn', 'vip.sina.com', 'msn.com', 'live.cn', 'hotmail.com', '263.net', 'sohu.com', 'vip.sohu.com', '139.com', '188.cn', '189.cn', 'sogou.com', 'foxmail.com', 'tom.com', 'yeah.net', 'yahoo.cn', 'yahoo.com', 'yahoo.com.cn', 'yahoo.com.hk', '21cn.com', '56.com', 'eyou.com', 'mail.china.com', 'aol.com', '163.net', 'xinhuanet.com');
		}
		
		$hosts = $this->MEmail->getHost($batch, $limit, $always);
		
		$this->assign('batch', $batch);
		$this->assign('label', $label);
		$this->assign('limit', $limit);
		$this->assign('always', $always);
		$this->assign('hosts', $hosts);
		
		$this->display();
	}

	public function fake() {
		$count = $fake = 0;
		
		$dir = \Core\HHO::$config['data.root'] . '/Fake';
		
		$dp = opendir($dir);
		
		while ($files = readdir($dp)) {
			if (in_array($files, array('.', '..'))) {
				continue;
			}
			
			$fp = fopen($dir . '/' . $files, 'r');
			
			FALSE && fseek($fp, 18000 * 4500);
			
			$data = '';
			
			while (TRUE) {
				$line = fgets($fp);
				
				if (feof($fp)) {
					break;
				}
				
				if (preg_match('/^\-\-.+\-\-$/', $line) && trim($line) != '--HHO.LIB.SMTP.BOUNDARY.ALTERNATIVE--') {
					$count++;
					
					$prefix = $host = '';
					
					if (preg_match('/@([\.\-\w]+)>:\s+Host\s+or\s+domain\s+name\s+not\s+found\./siU', $data, $tmp)) {
						$host = $tmp[1];
					} elseif (preg_match('/User\s*not\s+found:\s*([\.\-\w]+)@([\.\-\w]+)\s/siU', $data, $tmp)) {
						$prefix = $tmp[1];
						$host = $tmp[2];
					} elseif (preg_match('/\<([\.\-\w]+)@([\.\-\w]+)\>:.+Mailbox not\s+found/siU', $data, $tmp)) {
						$prefix = $tmp[1];
						$host = $tmp[2];
					} elseif (preg_match('/\<([\.\-\w]+)@([\.\-\w]+)\>:.+Inactive User/siU', $data, $tmp)) {
						$prefix = $tmp[1];
						$host = $tmp[2];
					} elseif (preg_match('/dd Sorry your message to\s+([\.\-\w]+)@([\.\-\w]+).+This\s+account\s+has\s+been\s+disabled\s+or\s+discontinued/siU', $data, $tmp)) {
						$prefix = $tmp[1];
						$host = $tmp[2];
					} elseif (preg_match('/dd This user doesn\'t have a yahoo.+ account\s+\(([\.\-\w]+)@([\.\-\w]+)\)\s+/siU', $data, $tmp)) {
						$prefix = $tmp[1];
						$host = $tmp[2];
					} elseif (preg_match('/\<([\.\-\w]+)@([\.\-\w]+)\>:.+host.+said:\s+550\s(.{256})/si', $data, $tmp)) {
						$tmp[3] = preg_replace('/\s+/', ' ', strtolower($tmp[3]));
						$tmp[3] = substr($tmp[3], 0, strpos($tmp[3], '--'));
						
						if (Lib\String::strpos($tmp[3], array('client host rejected', 'mailbox quota exceeded', 'unroutable address', 'mail from ip banned', 'denied by policy.', 'connection originating', 'allowed storage space'))) {
							// void
						} elseif (Lib\String::strpos($tmp[3], array('host unknown', 'blocked - see http', 'relay access denied', 'relay access denied.', 'relaying to <', 'relaying denied.', 'relaying denied (', 'relay denied (', 'this mail server requires smtp authentication'))) {
							$host = $tmp[2];
						} elseif (strpos($tmp[3], 'rcpt to') && Lib\String::strpos($tmp[3], array('invalid email', 'not a known user', 'specified address is not allowed', 'account not', 'mailbox name not', 'destination mailbox address', 'mailbox has moved', 'bad destination', 'account expired', 'in my badrcptto list', 'user is unknown', 'not known', 'illegal user', 'no such', 'invalid mailbox', ') unknown.', 'unable to deliver', 'is not a valid mailbox', 'unknown or illegal alias', 'unrouteable address', 'is now disabled', 'local user only', 'not exist', 'is disabled', 'user status is locked', 'recipient rejected', 'invalid recipient', 'bad address syntax', 'is absent', 'unavailable', 'mailbox disabled', 'unknown user', 'account is invalid', 'user not available', 'user disabled', 'invalid address', 'unable to relay', 'recipient unknown', 'not found', 'user not exist', 'user unknown', 'address rejected', 'mailbox not available', 'no mailbox', 'user locked', 'user suspended', 'account is disable', 'user invalid', 'invalid user', 'account that you tried to reach does no exist', 'no existe ese usuario', 'unknown email address', 'non-existent recipient', 'unknown recipient', 'mailbox is inactive', 'doesn\'t handle mail for that user'))) {
							$prefix = $tmp[1];
							$host = $tmp[2];
						} elseif (strpos($tmp[3], 'rcpt to') && !trim(substr($tmp[3], 0, strpos($tmp[3], '(')))) {
							$host = $tmp[2];
						} elseif (Lib\String::strpos($tmp[3], array('user', 'mailbox', 'address', 'expire', 'unknown', 'disable', 'exist', ' move', ' locked', 'syntax', 'invalid', 'available'))) {
							if (strpos($tmp[3], 'rcpt to')) {
								echo "({$count})Error 550:\r\n" . print_r($tmp, TRUE) . "\r\n\r\n\r\n";
							}
						}
					} elseif (preg_match('/\xef\xbc\x88([\.\-\w]+)@([\.\-\w]+)\xef\xbc\x89\xe5\x85\xb3\xe9\x97\xad\xe4\xba\x86\xe6\x95\xb0\xe5\xad\x97/s', iconv('GBK', 'UTF-8', $data), $tmp)) { // 未激活数字邮箱
						$prefix = $tmp[1];
						$host = $tmp[2];
					} elseif (preg_match('/\xef\xbc\x88([\.\-\w]+)@([\.\-\w]+)\xef\xbc\x89\xe7\x9a\x84\xe5\x8f\x8d\xe5\x9e/s', iconv('GBK', 'UTF-8', $data), $tmp)) { // 反垃圾设置拒绝
						$prefix = $tmp[1];
						$host = $tmp[2];
					} elseif (preg_match('/in reply to\s+end of DATA command/si', $data, $tmp)) {
						continue;
					}
					
					if (strpos($host, 'sinamail.sina.com.cn')) {
						if (preg_match('/\<([\.\-\w]+)@(sina[\.\-\w]+)\>/iU', $data, $tmp)) {
							$prefix = $tmp[1];
							$host = $tmp[2];
						} else {
							$prefix = $host = '';
						}
					}
					
					// 暂未激活网易手机邮账号
					if (!$host && strpos(iconv('GBK', 'UTF-8', $data), 'From: "网易邮件中心"<mail@service.netease.com>')) {
						$pos = strpos($data, 'Content-Transfer-Encoding: base64') + strlen('Content-Transfer-Encoding: base64') + 2;
						$tmp = substr($data, $pos);
						$tmp = base64_decode(substr($tmp, 0, strpos($tmp, '--------------') - 3));
						
						if (preg_match('/([\.\-\w]+)@([\.\-\w]+)/i', $tmp, $tmp)) {
							$prefix = $tmp[1];
							$host = $tmp[2];
						}
					}
					
					if ($prefix) {
						$fake++;
						
						$this->MEmail->delete(NULL, NULL, $prefix . '@' . $host);
					} elseif ($host && !in_array($host, array('qq.com', 'vip.qq.com', '163.com', 'vip.163.com', '126.com', 'gmail.com', 'sina.cn', 'sina.com', 'sina.com.cn', 'vip.sina.com', 'msn.com', 'live.cn', 'hotmail.com', '263.net', 'sohu.com', 'vip.sohu.com', '139.com', '188.cn', '189.cn', 'sogou.com', 'foxmail.com', 'tom.com', 'yeah.net', 'yahoo.cn', 'yahoo.com', 'yahoo.com.cn', 'yahoo.com.hk', '21cn.com', '56.com', 'eyou.com', 'mail.china.com', 'aol.com', '163.net', 'xinhuanet.com'))) {
						$fake++;
						
						$this->MEmail->delete(NULL, $host);
					}
					
					$data = '';
				} else {
					$data .= $line;
				}
			}
		}
		
		echo "{$fake}/{$count}";
	}

	public function history() {
		$dir = \Core\HHO::$config['data.root'] . '/History';
		
		$dp = opendir($dir);
		
		while ($files = readdir($dp)) {
			if (in_array($files, array('.', '..'))) {
				continue;
			}
			
			$data = explode("\r\n", file_get_contents($dir . '/' . $files));
			
			foreach ($data as $item) {
				$item = explode("\t", strtolower(trim($item)));
				if (count($item) != 4) {
					continue;
				}
				
				if (!is_numeric($item[0])) {
					continue;
				}
				
				if (!filter_var($item[1], FILTER_VALIDATE_EMAIL)) {
					continue;
				}
				
				$item[2] = strtotime($item[2]);
				
				$item[3] = bindec(decbin(ip2long($item[3])));
				
				if (!$this->MEmail->addHistory($item[1], $item[2], $item[3], $item[0])) {
					echo implode("\t", strtolower(trim($item))) . "\r\n";
				}
			}
		}
	}
}